// pages/myCars/myCars.ts
import { getSystemInfoSync } from '../../utils/util'
var url = require("../../utils/urls");
var commons = require("../../utils/common");
var tip = require("../../utils/tip");
var modelData = require("../../utils/data");
Page({

  /**
   * 页面的初始数据
   */
  data: {

    selectData: '车辆状态',
    selectDatas: ['空闲中', '保养中', '维修中'],
    selectDatas1: [
      {
        dicKey: 0,
        dicValue: "空闲中"
      },
      {
        dicKey: 2,
        dicValue: "保养中"
      }, {
        dicKey: 3,
        dicValue: "维修中"
      }
    ],
    index: '',
    startView: false, //控制下拉列表的显示隐藏，false隐藏、true显示
    systemInfo: {},
    pageData: {},
    tonnage: "",
    item: {},
    carNumber: '',
    businessStatus: "",
    maskShow: false,
    prepaidFreight: "",
    list: [],
    current: 1,
    size: 10,
    totalPage: 0,
    show: false,
    navigationBarTitleText: "我的车辆"
  },
  bindPickerChange: function (e) {
    // console.log(e.detail.value, 'e.detail.value')
    // let indexs = e.detail.value
    // this.setData({
    //   index: indexs,
    //   // '`[list$[index].startView]`' :true,
    //   [`list${indexs}.startView`]: true
    // })
    
    var that = this
    let list = that.data.list
    this.data.list.forEach(item => {
      if (item.carNumber == e.currentTarget.dataset.carnumber) {
        item['businessStateFont'] = this.data.selectDatas[e.detail.value];
        item['startView'] = true;
      }
    })


    let vehicleStatu = 0
    if (e.detail.value == 1) {
      vehicleStatu = 2
    } else if (e.detail.value == 2) {
      vehicleStatu = 3
    }
    let requestUrl = url.updateVehicleBusinessStatus
    let date = {
      carNumber: e.currentTarget.dataset.carnumber,
      vehicleStatus: vehicleStatu
      // vehicleStatus: this.data.selectDatas1[indexs]['dicKey']
    }
    // let data =  commons.post(requestUrl, date);
    commons.post(requestUrl, date).then(res => {
      console.log(res, 'resssssssssssssssss')
      if (res.code === 200) {
        tip.showToast(res.msg, 'success', 1000)
        this.myVehicle()
        // that.setData({
        //   list: this.data.list
        // });
      } else {
        tip.showToast(res.msg, 'error', 1000)
      }
    }).catch(err => {
      console.log(err, 'err000');
      tip.showToast(err.msg, 'error', 1000)
    });
    // this.myVehicle()
    // updateVehicleBusinessStatus 车辆状态（0：空闲中；2：保养中 3：维修中）
  },
  myVehicle: async function (e) {
    let json = {}
    let requestUrl = url.myVehicles
    if (e != null && e != '') {
      json = {
        current: this.data.current,
        size: this.data.size,
        carNumber: this.data.carNumber,
        businessStatus: this.data.businessStatus
      }
    } else if (e === 0) {
      json = {
        current: this.data.current,
        size: this.data.size,
        carNumber: this.data.carNumber,
        businessStatus: 0
      }
    }
    else {
      json = {
        current: this.data.current,
        size: this.data.size,
        carNumber: this.data.carNumber,
      }
    }


    let data = await commons.postJson(requestUrl + "?" + commons.getValue(json));

    if (data.code == 200) {
      let resData = data.data.idleVehicleRespVOS
      resData.records.forEach((item, index) => {
        item.businessStateFont = commons.getFont(modelData.businessStateData, item.businessState)
        resData.records.splice(index, 1, item)
      });
      this.setData({
        pageData: data.data,
        list: resData.records,
        show: true,
        totalPage: Math.ceil(resData.total / this.data.size)
      })
    } else {
      tip.showToast(data.msg, 'error', 1000)
    }
  },


  //拨打电话
  call(e) {
    let phone = e.currentTarget.dataset.phone
    commons.callPhone(phone)
  },
  businessStatus(e) {
    this.setData({
      businessStatus: e.target.dataset.status
    })
    let option = e.target.dataset.status
    this.myVehicle(option)

  },

  carNumberInput(e) {
    this.setData({
      current: 1,
      list: [],
      carNumber: e.detail.value
    })
    this.myVehicles()
  },

  tonnageInput(e) {
    this.setData({
      tonnage: e.detail.value
    })
  },

  prepaidFreightInput(e) {
    this.setData({
      prepaidFreight: e.detail.value
    })
  },

  myVehicles: async function (e) {
    let json = {}
    let requestUrl = url.myVehicles
    if (e != null && e != '') {
      json = {
        current: this.data.current,
        size: this.data.size,
        carNumber: this.data.carNumber,
        businessStatus: this.data.businessStatus
      }
    } else if (e === 0) {
      json = {
        current: this.data.current,
        size: this.data.size,
        carNumber: this.data.carNumber,
        businessStatus: 0
      }
    }
    else {
      json = {
        current: this.data.current,
        size: this.data.size,
        carNumber: this.data.carNumber,
      }
    }


    let data = await commons.postJson(requestUrl + "?" + commons.getValue(json));
    // console.log(data, '返回的数据')
    if (data.code == 200) {
      let resData = data.data.idleVehicleRespVOS
      for(let item of resData.records){
        item.startView =''

      }
      resData.records.forEach((item, index) => {
        item.businessStateFont = commons.getFont(modelData.businessStateData, item.businessState)
        resData.records.splice(index, 1, item)
      });
      this.setData({
        pageData: data.data,
        list: this.data.list.concat(resData.records),
        show: true,
        totalPage: Math.ceil(resData.total / this.data.size)
      })
    } else {
      tip.showToast(data.msg, 'error', 1000)
    }
  },

  goViewWaybill(e) {
    let item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: "../viewWaybill/viewWaybill?item=" + JSON.stringify(item),
    })
  },

  goBook(e) {
    let item = e.currentTarget.dataset.item
    wx.navigateTo({
      url: "../book/book?item=" + JSON.stringify(item),
    })
  },

  dispatch(e) {
    this.setData({
      maskShow: true,
      tonnage: "",
      item: e.currentTarget.dataset.item,
    })
  },

  cancel() {
    this.setData({
      maskShow: false,
    })
  },

  dispatchSure: async function () {
    if (!this.data.tonnage) {
      tip.showToast('请输入装车净重', 'error', 1000)
      return
    } else {
      if (this.data.tonnage > 99) {
        tip.showToast('吨数不能超出99', 'error', 1000)
        return
      }
    }

    if (!this.data.prepaidFreight) {
      tip.showToast('请输入预支费用', 'error', 1000)
      return
    }


    let requestUrl = url.savePlanDispatch
    let item = this.data.item
    let json = {
      "carNumber": item.carNumber,
      "driverName": item.driverName,
      "driverPhone": item.driverPhone,
      // "planId": this.data.planItem.id,
      "userId": item.driverId,
      "tonnage": this.data.tonnage,
      "prepaidFreight": this.data.prepaidFreight,
    }

    console.log(json, '参数')
    return

    let data = await commons.postJson(requestUrl, json);
    console.log(data, '返回的数据')
    if (data.code == 200) {
      tip.showToast(data.msg, 'success', 1000)
      this.myVehicles()
      this.setData({
        maskShow: false,
      })
    } else {
      tip.showToast(data.msg, 'error', 1000)
    }
  },

  loadMore(e) {
    console.log('加载更多')
    if (this.data.totalPage === 1) {
      return
    }

    if (this.data.current < this.data.totalPage) {
      this.setData({
        current: this.data.current + 1,
      })
      this.myVehicles()
      console.log(this.data.current, '当前页')
    }

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    let systemInfo = getSystemInfoSync()
    this.setData({
      systemInfo: systemInfo
    })
    this.myVehicles()
    console.log(systemInfo, 'systemInfo')
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    this.setData({
      current: 1,
      list: [],
      carNumber: ""
    })
    this.myVehicles()
    setTimeout(() => {
      wx.stopPullDownRefresh()
    }, 1000)
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})